package ltd.itlover.yqblog.main;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;

import android.os.Environment;
import android.provider.MediaStore;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropActivity;

import org.json.JSONObject;
import org.litepal.crud.DataSupport;


import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;

import javax.inject.Inject;


import dagger.hilt.android.AndroidEntryPoint;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import ltd.itlover.yqblog.R;
import ltd.itlover.yqblog.application.MyApplication;
import ltd.itlover.yqblog.blog.MainActivity;
import ltd.itlover.yqblog.dto.Result;
import ltd.itlover.yqblog.entity.User;
import ltd.itlover.yqblog.intent.IntentToLogin;
import ltd.itlover.yqblog.network.AccountApiService;
import ltd.itlover.yqblog.utils.TokenUtil;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

import retrofit2.HttpException;


/**
 * A simple {@link Fragment} subclass.
 * create an instance of this fragment.
 */
@SuppressWarnings("all")
@AndroidEntryPoint
public class MineFragment extends Fragment {
    @Inject
    AccountApiService accountApiService;
    ImageView myAvatarImg;
    TextView textMyUsername;
    Button logoutBtn;

    private static final int PHOTO_REQUEST_CAREMA = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 裁剪之后
    private static final String PHOTO_FILE_NAME = "temp_photo.jpg";//临时文件名
    private File tempFile;



    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {


        View view = inflater.inflate(R.layout.fragment_mine, container, false);

        logoutBtn = view.findViewById(R.id.btn_logout);
        myAvatarImg = view.findViewById(R.id.avatar_img);
        textMyUsername = view.findViewById(R.id.text_my_username);

        myAvatarImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new AlertDialog.Builder(getContext()).setTitle("上传头像")//设置对话框标题
                        .setPositiveButton("拍照", new DialogInterface.OnClickListener() {//添加确定按钮
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //调用系统相机的意图
                                camera();
                            }
                        }).setNegativeButton("系统相册", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            //调用系统图库的意图
                                gallery();
                            }
                }).show();
            }
        });

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();

        if (TokenUtil.getToken() != null){
            logoutBtn.setText("退出登录");
            logoutBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    requestLogout();
                }
            });
        }
        else{
            logoutBtn.setText("登录");
            logoutBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    IntentToLogin.toLoginPage();
                }
            });
        }

        requestMyInfoAndLoadToDatabase();

    }

    void requestLogout(){
        accountApiService.logout()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Result<String>>() {
                    @Override
                    public void accept(Result<String> stringResult) throws Exception {
                        makeInfo("成功注销");
                        TokenUtil.clearToken();
                        IntentToLogin.toLoginPage();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        if (throwable instanceof HttpException){
                            HttpException httpException = (HttpException) throwable;
                            String s = httpException.response().errorBody().string();
                            JSONObject jsonObject = new JSONObject(s);
                            makeInfo(jsonObject.getString("msg"));
                        }
                        else{
                            makeInfo("网络异常");
                        }

                    }
                });
    }
    void makeInfo(String msg){
        Toast.makeText(this.getContext(), msg, Toast.LENGTH_SHORT).show();
    }

    private void requestMyInfoAndLoadToDatabase(){
        accountApiService.getInfo()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Result<User>>() {
                    @Override
                    public void accept(Result<User> userResult) throws Exception {
                        User user = new User();
                        user = userResult.getData();
                        user.setToken(TokenUtil.getToken());
                        user.setUserId(user.getId());
                        user.save();
                        loadInfoToPage();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        loadInfoToPage();
                    }
                });
    }
    void loadInfoToPage(){
        User user = DataSupport.findLast(User.class);
        if(user != null){
            Glide.with(MainActivity.getMainContext()).load(TokenUtil.getImgDomain()+user.getAvatar())
                    .error(R.drawable.default_avatar).into(myAvatarImg);
            if (TokenUtil.getToken() == null){
                textMyUsername.setText("未登录");
            }
            else{
                textMyUsername.setText(user.getUsername());
            }
        }

    }

    //开启图库获取照片
    public void gallery() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, PHOTO_REQUEST_GALLERY);//携带请求码
    }

    //开启相机获取照片
    public void camera() {
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        if (hasSdcard()) {// 判断存储卡是否可以用，可用进行存储
            tempFile = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME);
            Uri uri = Uri.fromFile(tempFile); // 从文件中创建uri
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        }
        startActivityForResult(intent, PHOTO_REQUEST_CAREMA);//携带请求码
    }



    //判断是否挂在了SD卡
    private boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    //获取的是external数据库对应的Image文件
    private Uri external(String external) {
        String myImageUrl = "content://media" + external;
        Uri uri = Uri.parse(myImageUrl);
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor actualimagecursor = this.getActivity().managedQuery(uri, proj, null, null, null);
        int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        actualimagecursor.moveToFirst();
        String img_path = actualimagecursor.getString(actual_image_column_index);
        File file = new File(img_path);
        Uri fileUri = Uri.fromFile(file);
        return fileUri;
    }


    private void upLoad2Server(Uri uri) {
        File file = null;
        try {
            file = new File(new URI(uri.toString()));
            Log.i("申请上传的时候拿到的文件",file.length()+"");
        } catch (Exception e) {
            Log.i("获取文件失败", "");
            e.printStackTrace();
        }

        Log.i("申请上传的时候拿到的文件",file.length()+"");
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/all"), file);
        Log.i("requestBody", requestBody+"");

        MultipartBody.Part body = MultipartBody.Part.createFormData("userIcon", file.getName(), requestBody);
        Log.i("Body后", body+"");
        myAvatarImg.setEnabled(false);
        accountApiService.uploadAvatar(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Result<String>>() {
                    @Override
                    public void accept(Result<String> stringResult) throws Exception {
                        makeInfo("上传成功");
                        myAvatarImg.setEnabled(true);
                        requestMyInfoAndLoadToDatabase();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        makeInfo("上传失败");
                        myAvatarImg.setEnabled(true);
                        requestMyInfoAndLoadToDatabase();
                    }
                });
    }


    //在回调中取图片
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PHOTO_REQUEST_GALLERY) {
            // 从相册返回的数据
            if (data != null) {// 得到图片的全路径
//                makeInfo("响应了结果");
                Uri uri = data.getData();
                crop(uri);
            }
        }
        else if (requestCode == PHOTO_REQUEST_CAREMA) {//从相机返回的数据
            if (hasSdcard()) {
                crop(Uri.fromFile(tempFile));
            } else {
                Toast.makeText(this.getActivity(), "未找到存储卡，无法存储照片！", Toast.LENGTH_LONG).show();
            }
        }
        else if (requestCode == UCrop.REQUEST_CROP) {//从剪切图片返回的数据
            //makeInfo("123");
            if (data != null) {
                //makeInfo(data.getData()+"");
                Uri uri = UCrop.getOutput(data);
                Log.i("回调中拿到的URI", uri.toString());
                upLoad2Server(uri);
            }
            try {
                tempFile.delete();//将临时文件删除
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    //裁剪图片
    private void crop(Uri srcUri) {
        //裁剪后保存到文件中
//        makeInfo(srcUri.toString());
        long time = System.currentTimeMillis();
        File fileExist = new File(srcUri.toString());
        String name = fileExist.getName();
        File file = new File(MyApplication.getContext().getFilesDir(), name);
        Uri destinationUri = Uri.fromFile(file);
        UCrop uCrop = UCrop.of(srcUri, destinationUri);
        UCrop.Options options = new UCrop.Options();
        //设置裁剪图片可操作的手势
        options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);
        //设置隐藏底部容器，默认显示
//        options.setHideBottomControls(true);
        //设置toolbar颜色
        options.setToolbarColor(ActivityCompat.getColor(this.getContext(), android.R.color.holo_red_light));
        //设置状态栏颜色
        options.setStatusBarColor(ActivityCompat.getColor(this.getContext(), android.R.color.holo_red_light));
        options.setCompressionFormat(Bitmap.CompressFormat.JPEG);
        //是否能调整裁剪框
//        options.setFreeStyleCropEnabled(true);
        uCrop.withOptions(options);
        uCrop.start(this.getContext(), this);
    }
}